package com.gitee.fsmxm.ocd.controller;

import com.gitee.fsmxm.ocd.config.DocumentConverterConfig;
import com.gitee.fsmxm.ocd.exception.BaseException;
import com.gitee.fsmxm.ocd.model.Result;
import com.gitee.fsmxm.ocd.service.DirectoryCleanScheduler;
import com.gitee.fsmxm.ocon.DocumentConverter;
import com.gitee.fsmxm.ocon.constant.AppEnum;
import com.gitee.fsmxm.ocon.core.ConvertException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author fsmxm
 */
@Slf4j
@RestController
public class ConvertController {

    @Autowired
    private DocumentConverterConfig documentConverterConfig;

    @Autowired
    private DocumentConverter documentConverter;

    @Autowired
    private DirectoryCleanScheduler scheduler;

    @RequestMapping("/convert")
    public Result convert(@RequestParam("file") MultipartFile file,
                          @RequestParam("app") String app,
                          @RequestParam("to") String to) throws BaseException {
        if (file == null) {
            throw new BaseException("5556", "文件未上传");
        }
        final String fileName = file.getOriginalFilename();

        if (fileName == null) {
            throw new BaseException("5556", "文件未上传");
        }

        File transferPath = null;

        try {
            final File tempDir = documentConverterConfig.getTempDir();
            final File transferDir = documentConverterConfig.getTransferDir();
            final File downDir = documentConverterConfig.getDownDir();

            final String path = new SimpleDateFormat("yyyy/MM").format(new Date());

            final File tempPath = new File(tempDir, path + "/" + UUID.randomUUID().toString());
            transferPath = new File(transferDir, path + "/" + UUID.randomUUID().toString());
            final File downPath = new File(downDir, path);

            if (!tempPath.exists() && !tempPath.mkdirs()) {
                log.error("创建路径失败: " + tempPath.getAbsolutePath());
                throw new BaseException("5557", "文件上传失败");
            }

            if (!transferPath.exists() && !transferPath.mkdirs()) {
                log.error("创建路径失败: " + transferPath.getAbsolutePath());
                throw new BaseException("5557", "文件上传失败");
            }

            if (!downPath.exists() && !downPath.mkdirs()) {
                log.error("创建路径失败: " + downPath.getAbsolutePath());
                throw new BaseException("5557", "文件上传失败");
            }

            final String ext = com.gitee.fsmxm.ocon.util.IOUtils.getExt(fileName);

            final File sourceFile = new File(tempPath, fileName);

            try (InputStream input = file.getInputStream();
                 OutputStream output = new FileOutputStream(sourceFile)) {
                IOUtils.copy(input, output);
            } catch (Exception e) {
                throw new BaseException("5557", "文件上传失败", e);
            }


            final String newName = fileName.substring(0, fileName.length() - ext.length() - 1);

            final File targetFile = new File(transferPath, newName + "." + to);

            final AppEnum appEnum = AppEnum.getInstance(app);

            try {
                final int res = documentConverter.convert(sourceFile, targetFile, appEnum, 1000);
                if (res == -1) {
                    throw new BaseException("8888", "服务忙，请稍后再试");
                }
            } catch (ConvertException e) {
                log.error("error: ", e);
                throw new BaseException("5558", "文件转换失败", e);
            }

            try {
                FileUtils.copyDirectoryToDirectory(transferPath, downPath);
            } catch (IOException e) {
                log.error("error: ", e);
                throw new BaseException("5558", "文件转换失败", e);
            }

            final String absolutePath = targetFile.getAbsolutePath();
            final String filePah = absolutePath.substring(transferDir.getAbsolutePath().length()).replace("\\", "/");

            final String downUrl = documentConverterConfig.getDownUrl();

            return new Result("2000", "转换成功", downUrl + "/" + filePah);
        } finally {
            if (transferPath != null) {
                FileUtils.deleteQuietly(transferPath);
                if (transferPath.exists()) {
                    scheduler.offer(transferPath);
                }
            }
        }

    }

}
